'use strict'

import {app, protocol, BrowserWindow, Menu, MenuItemConstructorOptions, MenuItem, globalShortcut, Tray} from 'electron'
import {createProtocol} from 'vue-cli-plugin-electron-builder/lib'
// @ts-ignore
import installExtension, {VUEJS_DEVTOOLS} from 'electron-devtools-installer'
import {registerShortCut} from "@/electron/shortcut_key";
import "./electron/main";
import {MAIN_STORE} from "@/electron/main";
import * as electron from "electron";
import {getSelectedNote} from "@/electron/application";
import {gitPull} from "@/utils/main/git.utils";
import path from "path"
import {NOTES_DIR} from "@/electron/const";
import {mkDir} from "@/utils/main/file.uitls";


const isDevelopment = process.env.NODE_ENV !== 'production'

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
    {scheme: 'app', privileges: {secure: true, standard: true}}
])

mkDir(NOTES_DIR);

let win = null;
let lastGitPull = 0;

async function createWindow() {

    // Create the browser window.
    win = new BrowserWindow({
        width: MAIN_STORE.config.windowWidth,
        height: MAIN_STORE.config.windowHeight,
        webPreferences: {

            // Use pluginOptions.nodeIntegration, leave this alone
            // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
            // @ts-ignore
            nodeIntegration: true, //process.env.ELECTRON_NODE_INTEGRATION
        },
        // @ts-ignore
        icon: `${__static}/app.ico`,
    });
    MAIN_STORE.win = win;
    win.on('minimize', (e) => {
    });
    win.on("focus", (e): void => {
        let now = new Date().getTime();
        if (now - lastGitPull < 180000) return;
        let note = getSelectedNote();
        if (!note) return;
        lastGitPull = now;
        gitPull(note.path);
    })
    win.on('close', (e) => {
        e.preventDefault();
        win.hide();
        return;
        electron.dialog.showMessageBox({
            type: 'info',
            title: '提示',
            message: '确认退出？',
            buttons: ['确认', '隐藏到托盘'],   //选择按钮，点击确认则下面的idx为0，取消为1
            cancelId: 1, //这个的值是如果直接把提示框×掉返回的值，这里设置成和“取消”按钮一样的值，下面的idx也会是1
        }).then(idx => {
            //注意上面↑是用的then，网上好多是直接把方法做为showMessageBox的第二个参数，我的测试下不成功
            if (idx.response == 1) {
                e.preventDefault();
                win.hide();
            } else {
                app.quit();
            }
        })
    });
    createMenu(win);

    if (process.env.WEBPACK_DEV_SERVER_URL) {
        // Load the url of the dev server if in development mode
        await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
        if (!process.env.IS_TEST) win.webContents.openDevTools()
    } else {
        createProtocol('app')
        // Load the index.html when not in development
        win.loadURL('app://./index.html')
    }
    registerShortCut(win);
}

function createMenu(win) {
    // darwin -> macOS
    if (process.platform === 'darwin') {
        const template: Array<MenuItemConstructorOptions | MenuItem> = [{
            label: 'GitNotebook',
            submenu: [
                {role: 'about'},
                {role: 'quit'},
            ]
        }];
        let menu = Menu.buildFromTemplate(template);
        Menu.setApplicationMenu(menu);
    } else {
        // windows & linus ...
        Menu.setApplicationMenu(null);
    }
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q

    if (process.platform !== 'darwin') {
        app.quit();
    }
})

app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (win === null) createWindow()
})

let tray = null;
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
    if (isDevelopment && !process.env.IS_TEST) {
        // Install Vue Devtools
        try {
            await installExtension(VUEJS_DEVTOOLS)
        } catch (e) {
            console.error('Vue Devtools failed to install:', e.toString())
        }
    }
    await createWindow()
    // @ts-ignore
    tray = new Tray(`${__static}/app.ico`);
    const contextMenu = Menu.buildFromTemplate([
        {
            label: '退出',
            click: () => {
                app.quit();
                app.quit();
                app.exit();
            }
        }
    ]);
    tray.setToolTip("git-notebook");
    tray.setContextMenu(contextMenu);
    tray.on("click", () => {
        if (!win.isVisible()) {
            win.show()
        }
    })
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
    if (process.platform === 'win32') {
        process.on('message', (data) => {
            if (data === 'graceful-exit') {
                app.quit()
            }
        })
    } else {
        process.on('SIGTERM', () => {
            app.quit()
        })
    }
}
